#! /usr/bin/perl
my $source = "";

my $compress = 1;
if ($ARGV[0] eq "-nc") {
  $compress = 0;
  shift @ARGV;
}

binmode STDOUT;

my $output = "";
while (<>) {
  next if /^\s*[|\\]\s/ || /^\s*$/
          || /^\s*((purpose)|(license)|(copyright)|(status)):\s/;
  $source .= $_;
}
my @table;
sub word {
  my $word = shift;
  my $k = ( (length($word) << 4)
          ^ ( ord(substr($word, length($word) >> 1)) << 2 )
          ^ ord($word) ) & 255;
  $k = 3 if $k < 3;
  if ($table[$k] ne $word) {
    $table[$k] = $word;
    return chr(1). substr($word, 0, length($word) - 1).
          chr(ord(substr($word, -1)) | 128);
  }
  return chr($k);
}
while ($source =~ /(\S+)/g) {
  my $word = $1;
  if ($word eq "help:") {
    $source =~ /\G\s([^\n]+)\n/g or die "wrong source";
    $word .= " $1";
    $output .= chr(2).word("e\"").$word.chr(0);
  } elsif ($word eq ":" or $word eq "[']") {
    $source =~ /(\S+)/g or die "wrong source";
    $output .= word($word).word($1);
  } else {
    $output .= chr(2) if ($word =~ /"$/ && $word ne "'\"" && $word ne "\"\"");
    $output .= word($word);
    if ($word =~ /"$/ && $word ne "'\"" && $word ne "\"\"") {
      $source =~ /\G\s([^"]*)"/g or die "wrong source";
      $output .=  $1.chr(0);
    }
  }
}
$output .= chr(0);
my $used = 0;
for (0..255) { $used++ if defined $table[$_]; }
print STDERR "$used bytecodes used.\n";

if ($compress) {
  open FILE, ">~~bctemp~~";
  print FILE length($output)." 4p-bytecode ".$output."\n";
  close FILE;

  my $altout = `helper/mkzip ~~bctemp~~`;

  if (length($altout) / length($output) < 0.9) {
     print $altout;
     exit 0;
  }
}
print length($output)." 4p-bytecode ".$output."\n";
